package com.fearless.test02;
/*

    使用JUC来完成生产者，消费者问题

 */


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//共享类。提供共享变量 和方法
public class Repository {
    private int count=0;

    Lock lock=new ReentrantLock(true);
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();

    synchronized void consume()  {

        condition2.signal();
        lock.lock();

        try {
            if(count>0){
                System.out.println("当前库存是"+count+Thread.currentThread().getName()+"进行消费");
                count--;
            }else {
                condition1.await();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

    synchronized void produce() {


        lock.lock();
        condition1.signalAll();

        try {

            if(count==0){
                System.out.println("当前库存是"+count+Thread.currentThread().getName()+"进行生产");
                count++;


            }else {
                condition2.await();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }



    }



}

class Test02{
    public static void main(String[] args) {

        Repository repository=new Repository();


        new Thread(()->{
            for (int i = 0; i <20 ; i++) {
                repository.produce();
            }
        },"生产者").start();


        new Thread(()->{
            for (int i = 0; i <20 ; i++) {
                repository.consume();
            }
        },"消费者").start();


    }

}